import { defineStore } from "pinia";
import { STORE_PREFIX } from "@/utils/constant";
import { cloneDeep, find, uniqBy } from "lodash-es";
import { reqChatContentList } from "@/api/main";

const formatArr = (old: ChatContentMo[], list: ChatContentMo[]) => {
  const uniqList = uniqBy(list, "UserId"); // 去重
  const filteredOldArray = uniqList
    .map(
      item => find(old, e => String(e.UserId) === String(item.UserId)) // 查找旧数组中对应项
    )
    .filter(Boolean) as ChatContentMo[]; // 过滤掉找不到的项
  return filteredOldArray;
};

export const useServiceStore = defineStore(
  `${STORE_PREFIX}service_store`,
  () => {
    const status = ref<boolean>(false);
    const tabActive = ref(false);
    const serviceActive = ref(0);
    const serviceCount = ref(0);
    const serviceList = ref<ChatContentMo[]>([]);
    const serviceState = ref({
      Page: 1,
      PageSize: 200,
      TotalPage: 9999,
      Name: "",
      SortField: "time"
    });

    const getStatus = computed(() => status.value);
    const getServiceList = computed(() => serviceList.value);

    const setStatus = (b: boolean) => {
      status.value = b;
    };
    const setTabActive = (b: boolean) => {
      tabActive.value = b;
    };
    const setServiceActive = (b: number) => {
      serviceActive.value = b;
    };

    const actionServiceList = async (id?: string) => {
      try {
        const res = await reqChatContentList({
          Page: serviceState.value.Page,
          PageSize: serviceState.value.PageSize,
          SortField: serviceState.value.SortField
        });
        let oldList = cloneDeep(serviceList.value);
        const list = res.data.List || [];
        let newList = cloneDeep(formatArr(oldList, list));
        // 去重
        newList = cloneDeep(uniqBy(newList, "UserId"));
        for (let i = 0; i < list.length; i++) {
          const item = list[i];
          const oldItem = newList.find(e => String(e.UserId) === String(item.UserId));
          if (oldItem) {
            newList[i] = {
              ...item,
              Count: oldItem.Count
            };
          } else {
            newList.push({
              ...item,
              Count: id && id == item.UserId ? 1 : 0
            });
          }
        }
        serviceState.value.TotalPage = Math.ceil(res.data.Total / serviceState.value.PageSize);
        serviceList.value = cloneDeep(newList);
      } catch (error) {
        console.log(error);
      }
    };

    const addService = (item: ChatContentMo) => {
      serviceList.value.push(item);
    };

    const removeService = (item: ChatContentMo) => {
      serviceList.value = cloneDeep(
        serviceList.value.filter((i: ChatContentMo) => i.UserId !== item.UserId)
      );
    };
    const updateServiceCountItem = (uid: number, flag: boolean = false) => {
      const services = cloneDeep(serviceList.value);
      for (let i = 0; i < services.length; i++) {
        if (Number(services[i].UserId) == Number(uid)) {
          services[i] = cloneDeep({
            ...services[i],
            Count: flag ? 0 : (services[i].Count! as number) + 1
          });
          break;
        }
      }
      serviceList.value = cloneDeep(services);
    };
    const updateServiceItem = (mo: ChatContentMo) => {
      const services = cloneDeep(serviceList.value);
      for (let i = 0; i < services.length; i++) {
        if (Number(services[i].UserId) == Number(mo.UserId)) {
          services[i] = cloneDeep({
            ...services[i],
            ...mo
          });
          break;
        }
      }
      serviceList.value = cloneDeep(services);
    };
    watch(
      () => serviceList.value,
      val => {
        let flag = false;
        val.forEach(item => {
          if (item.Count! > 0) {
            flag = true;
          }
        });
        serviceCount.value = val.filter(item => item.Count! > 0).reduce((a, b) => a + b.Count!, 0);
        status.value = flag;
      }
    );
    return {
      status,
      tabActive,
      serviceActive,
      serviceList,
      serviceState,
      serviceCount,
      getStatus,
      getServiceList,
      setStatus,
      setTabActive,
      setServiceActive,
      addService,
      removeService,
      actionServiceList,
      updateServiceItem,
      updateServiceCountItem
    };
  },
  {
    persist: {
      storage: localStorage
    }
  }
);
